package com.chris.core.socket.netty.handler.heatbeat;

import com.chris.core.socket.netty.dto.protocol.CustomMessageProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 自定义 - 编码 - 心跳处理器
 */
public class HeatBeatCustomHandler extends ChannelInboundHandlerAdapter {

   // private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 用户自定义心跳事件，重载
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
       // super.userEventTriggered(ctx, evt);
        if(evt instanceof IdleStateEvent)
        {
            IdleStateEvent event = (IdleStateEvent)evt;
            String eventType=null;
            //writeAndFlush中传递的数据必须转换为Object后才能传输，否则出现数据没有的问题！(这个才是坑)
            CustomMessageProtocol dto ;
            switch (event.state()) {
                case READER_IDLE:
                    eventType="读空闲";
                    // dto= new CmdMessageProtocol("cmd","ping");
                    dto = new CustomMessageProtocol();
                    dto.setContentSystemCmd("ping");
                    // ctx.channel().writeAndFlush(dto);
                    ctx.writeAndFlush(dto);
                    break;
                case  WRITER_IDLE:
                    eventType="写空闲";
                   //   dto= new CmdMessageProtocol("cmd","ping");
                    dto = new CustomMessageProtocol();
                    dto.setContentSystemCmd("ping");
                    //ctx.channel().writeAndFlush(dto);
                    ctx.writeAndFlush(dto);
                    break;
                case ALL_IDLE:
                    eventType="读写空闲";
                    break;
            }
           // log.debug("心跳:"+eventType);
        }
    }
}
